<?php


namespace app\api\controller\xilujob;


use app\common\controller\xilujob\XilujobApi;
use app\admin\model\Third\RecruitmentMeeting as RecruitmentMeetingModel;
use app\admin\model\Third\RecruitmentCompany as RecruitmentCompanyModel;
use app\admin\model\Third\RecruitmentJob as RecruitmentJobModel;

use app\admin\model\Third\LiveChannel as LiveChannelModel;
use app\admin\model\Third\LiveJob as LiveJobModel;
use app\admin\model\Third\LiveCompany as LiveCompanyModel;


/**
 * 二开
 */
class Third extends XilujobApi
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function getSettings()
    {
        $data = [];
        $data['industry_category'] = \app\admin\model\xilujob\IndustryCategory::order('weigh')->column('id,name');

        $data['scales'] = \app\admin\model\xilujob\CompanyScale::column('id,name');

        $data['company_types'] = \app\admin\model\xilujob\CompanyProperties::order('weigh')->column('id,name');

        $data['education_level'] = \app\admin\model\xilujob\EducationLevel::order('weigh')->column('id,name');

        $this->success('ok', $data);
    
    }
    
    // 获取招聘会列表
    public function getRecruitmentList()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);

        $now = time();
        
        // 使用子查询来获取所有记录并计算状态
        $query = RecruitmentMeetingModel::where('status', 'normal')
            ->field('id, title, banner_image, starttime, endtime')
            ->field("CASE 
                WHEN {$now} >= starttime AND {$now} <= endtime THEN 1 
                WHEN {$now} < starttime THEN 2 
                ELSE 3 
            END as status_order")
            ->buildSql();

        $list = RecruitmentMeetingModel::table($query . ' a')
            ->order('a.status_order', 'asc')
            ->order('a.starttime', 'asc')
            ->page($page, $limit)
            ->select();

        $total = RecruitmentMeetingModel::where('status', 'normal')->count();

        foreach ($list as &$item) {
            if ($now < $item['starttime']) {
                $item['status_name'] = '未开始';
            } elseif ($now >= $item['starttime'] && $now <= $item['endtime']) {
                $item['status_name'] = '进行中';
            } else {
                $item['status_name'] = '已结束';
            }
            $item['banner_image'] = cdnurl($item['banner_image'], true);
            unset($item['status_order']); // 移除临时排序字段
        }
        unset($item);

        $this->success('获取成功', [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }

    // 获取招聘会详情
    public function getRecruitmentDetail() 
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数错误');
        }

        // 获取招聘会详情
        $meeting = RecruitmentMeetingModel::where('status', 'normal')
            ->where('id', $id)
            ->find();
            
        if (!$meeting) {
            $this->error('招聘会不存在');
        }


        $isApply = 0;
        $now = time();
        if ($meeting['starttime'] < $now && $meeting['endtime'] > $now) {
            $isApply = 1;
        }
        $meeting['is_apply'] = $isApply;

        $meeting['start'] = date('m/d', $meeting['starttime']);
        $meeting['end'] = date('m/d', $meeting['endtime']);

        // 处理banner图片
        $meeting['banner_image'] = cdnurl($meeting['banner_image'], true);
        
        // 处理way字段
        $meeting['way_text'] = $meeting['way'] == 1 ? '线上' : '线下';
        unset($meeting['starttime_text'], $meeting['endtime_text'], $meeting['status_text']);

        // 获取推荐企业列表
        $recommendCompanies = RecruitmentCompanyModel::where('recruitment_meeting_id', $id)
            ->where('is_recommend', 1)
            ->field('name, logo_image')
            ->where('status', 1)
            ->select();
        foreach ($recommendCompanies as &$r) {
            $r['name'] = mb_substr($r['name'], 0, 5);
            $r['logo_image'] = cdnurl($r['logo_image'], true);
        }

        $this->success('获取成功', [
            'meeting' => $meeting,
            'recommend_companies' => $recommendCompanies
        ]);
    }

    // 获取招聘会企业列表
    public function getRecruitmentCompanyList()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数错误');
        }

        // 获取招聘会详情
        $meeting = RecruitmentMeetingModel::where('status', 'normal')
            ->where('id', $id)
            ->find();
            
        if (!$meeting) {
            $this->error('招聘会不存在');
        }

        $companyList = RecruitmentCompanyModel
          ::where('recruitment_meeting_id', $id)
            ->where('status', '1')
            ->with([
                'company_scale'=>function($query){$query->withField('id,name');},
                'company_properties'=>function($query){$query->withField('id,name');},
                'industry_category'=>function($query){$query->withField('id,name');},
            ])
            ->page($page, $limit)
            ->select();

        $total = RecruitmentCompanyModel::where('recruitment_meeting_id', $id)->where('status', '1')->count();

        $companyIds = [];
        foreach ($companyList as &$company) {
            $company['logo_image'] = cdnurl($company['logo_image'], true);
            $companyIds[] = $company['id'];
        }
        unset($company);

        $jobs = RecruitmentJobModel::where('recruitment_company_id', 'in', $companyIds)
            ->field('id, title,recruitment_company_id')
            ->select();
            
        $companyJobs = [];
        foreach ($jobs as $job) {
            if (!isset($companyJobs[$job['recruitment_company_id']])) {
                $companyJobs[$job['recruitment_company_id']] = [];
            }
            $companyJobs[$job['recruitment_company_id']][] = $job;
        }
        
        foreach ($companyList as &$company) {
            $company['jobs'] = isset($companyJobs[$company['id']]) ? $companyJobs[$company['id']] : [];
        }
        unset($company);

        $this->success('获取成功', [
            'list' => $companyList,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }

    // 获取招聘会企业详情
    public function getRecruitmentCompanyDetail()
    {
        // 1.get方式获取入参company_id,如果此参数不存在，需要报错
        $companyId = $this->request->get('company_id');
        if (!$companyId) {
            $this->error('参数错误');
        }

        // 2.根据companyId到RecruitmentCompanyModel查询报名企业信息,如果企业信息不存在，也需要报错
        $company = RecruitmentCompanyModel::where('recruitment_company.id', $companyId)
            ->where('status', 1)
            ->with([
                'industry_category' => function($query) { $query->withField('id,name'); },
                'company_scale' => function($query) { $query->withField('id,name'); },
                'company_properties' => function($query) { $query->withField('id,name'); }
            ])
            ->find();
            
        if (!$company) {
            $this->error('企业信息不存在');
        }

        // 3.将industry_category_id,company_scale_id,company_type_id转为对应的名称
        $company['industry_category_name'] = $company['industry_category']['name'] ?? '';
        $company['company_scale_name'] = $company['company_scale']['name'] ?? '';
        $company['company_type_name'] = $company['company_properties']['name'] ?? '';

        // 4.根据company_id到RecruitmentJobModel查询所有岗位记录
        $jobs = RecruitmentJobModel::where('recruitment_company_id', $companyId)
            ->field('id,title,salary,education_level_id,descr')
            ->select();

        // 5.岗位记录中将education_level_id转为对应的文字
        $educationLevels = \app\admin\model\xilujob\EducationLevel::column('name', 'id');
        foreach ($jobs as &$job) {
            $job['education_level_name'] = $educationLevels[$job['education_level_id']] ?? '';
        }
        unset($job);

        // 6.将岗位记录作为企业信息的一个属性后进行返回
        $company['jobs'] = $jobs;
        $company['logo_image'] = cdnurl($company['logo_image'], true);
        unset($company['industry_category'], $company['company_scale'], $company['company_properties']);

        $this->success('获取成功', $company);
    }

    // 申请招聘会企业信息，包括填写职位信息
    public function applyRecruitment()
    {
        $params = input('post.');
        if (empty($params['recruitment_meeting_id'])) {
            $this->error('缺少主参数');
        }
        if (empty($params['name'])) {
            $this->error('缺少企业名称');
        }
        if (empty($params['contact_person'])) {
            $this->error('缺少联系人');
        }
        if (empty($params['contact_phone'])) {
            $this->error('缺少联系人电话');
        }
        if (!empty($params['address']) && (empty($params['longitude']) || empty($params['latitude']))) {
            $this->error('有地址信息时，请选择经纬度');
        }
        if (empty($params['logo_image'])) {
            $this->error('请上传企业Logo');
        }
        if (empty($params['other_images'])) {
            $this->error('请上传企业执照或相关证件');
        }
        if (!empty($params['other_images'])) {
            $params['other_images'] = implode(",", $params['other_images']);
        }
        $check = RecruitmentCompanyModel::where('name', 'like', '%'.$params['name'].'%')->find();
        // 如果存在
        $jobs = $params['jobs'];
        unset($params['jobs']);
        if ($check) {
            if ($check->status == '1' || $check->status == '0') {
                $this->error('企业信息重复');
            }
            // 再次提交，标记为未审核
            $check->status = '0';
            $check->name = $params['name'];
            $check->industry_category_id = $params['industry_category_id'];
            $check->company_scale_id = $params['company_scale_id'];
            $check->company_type_id = $params['company_type_id'];
            $check->contact_person = $params['contact_person'];
            $check->contact_phone = $params['contact_phone'];
            $check->address = !empty($params['address']) ? $params['address'] : '';
            $check->longitude = !empty($params['longitude']) ? $params['longitude'] : '';
            $check->latitude = !empty($params['latitude']) ? $params['latitude'] : '';

            $check->intro = $params['intro'];
            $check->logo_image = $params['logo_image'];
            $check->other_images = $params['other_images'];
            $check->save(); 
        } else {
            $check = new RecruitmentCompanyModel();
            $params['job_total'] = count($jobs);
            $check->save($params);
        }
        $companyId = $check->id;

        foreach ($jobs as $job) {
            $jobModel = new RecruitmentJobModel();            
            $job['recruitment_meeting_id'] = $params['recruitment_meeting_id'];
            $job['recruitment_company_id'] = $companyId;
            $job['status'] = 0;
            $jobModel->save($job);
        }

        $this->success('提交成功，请等待审核!');
    }


    // 获取直播频道列表
    public function getLiveList()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);

        $now = time();
        
        // 使用子查询来获取所有记录并计算状态
        $query = LiveChannelModel::where('status', 'normal')
            ->field('id, title, banner_image, starttime, endtime')
            ->field("CASE 
                WHEN {$now} >= starttime AND {$now} <= endtime THEN 1 
                WHEN {$now} < starttime THEN 2 
                ELSE 3 
            END as status_order")
            ->buildSql();

        $list = LiveChannelModel::table($query . ' a')
            ->order('a.status_order', 'asc')
            ->order('a.starttime', 'asc')
            ->page($page, $limit)
            ->select();

        $total = LiveChannelModel::where('status', 'normal')->count();

        foreach ($list as &$item) {
            if ($now < $item['starttime']) {
                $item['status_name'] = '未开始';
            } elseif ($now >= $item['starttime'] && $now <= $item['endtime']) {
                $item['status_name'] = '进行中';
            } else {
                $item['status_name'] = '已结束';
            }
            $item['banner_image'] = cdnurl($item['banner_image'], true);
            unset($item['status_order']); // 移除临时排序字段
        }
        unset($item);

        $this->success('获取成功', [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }

    // 获取招聘会详情
    public function getLiveDetail() 
    {
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数错误');
        }

        // 获取招聘会详情
        $meeting = LiveChannelModel::where('status', 'normal')
            ->where('id', $id)
            ->find();
            
        if (!$meeting) {
            $this->error('直播频道不存在');
        }


        $isApply = 0;
        $now = time();
        if ($meeting['starttime'] < $now && $meeting['endtime'] > $now) {
            $isApply = 1;
        }
        $meeting['is_apply'] = $isApply;

        $meeting['start'] = date('m/d', $meeting['starttime']);
        $meeting['end'] = date('m/d', $meeting['endtime']);

        // 处理banner图片
        $meeting['banner_image'] = cdnurl($meeting['banner_image'], true);
        

        // 获取推荐企业列表
        $recommendCompanies = LiveCompanyModel::where('live_channel_id', $id)
            ->where('is_recommend', 1)
            ->field('name, logo_image')
            ->where('status', 1)
            ->select();
        foreach ($recommendCompanies as &$r) {
            $r['name'] = mb_substr($r['name'], 0, 5);
            $r['logo_image'] = cdnurl($r['logo_image'], true);
        }

        $this->success('获取成功', [
            'live_info' => $meeting,
            'recommend_companies' => $recommendCompanies
        ]);
    }

    // 获取招聘会企业列表
    public function getLiveCompanyList()
    {
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $id = $this->request->get('id');
        if (!$id) {
            $this->error('参数错误');
        }

        // 获取招聘会详情
        $meeting = LiveChannelModel::where('status', 'normal')
            ->where('id', $id)
            ->find();
            
        if (!$meeting) {
            $this->error('直播频道不存在');
        }

        $companyList = LiveCompanyModel 
          ::where('live_channel_id', $id)
            ->where('status', '1')
            ->with([
                'company_scale'=>function($query){$query->withField('id,name');},
                'company_properties'=>function($query){$query->withField('id,name');},
                'industry_category'=>function($query){$query->withField('id,name');},
            ])
            ->page($page, $limit)
            ->select();

        $total = LiveCompanyModel::where('live_channel_id', $id)->where('status', '1')->count();

        $companyIds = [];
        foreach ($companyList as &$company) {
            $company['logo_image'] = cdnurl($company['logo_image'], true);
            $companyIds[] = $company['id'];
        }
        unset($company);

        $jobs = LiveJobModel::where('live_company_id', 'in', $companyIds)
            ->field('id, title,live_company_id')
            ->select();
            
        $companyJobs = [];
        foreach ($jobs as $job) {
            if (!isset($companyJobs[$job['live_company_id']])) {
                $companyJobs[$job['live_company_id']] = [];
            }
            $companyJobs[$job['live_company_id']][] = $job;
        }
        
        foreach ($companyList as &$company) {
            $company['jobs'] = isset($companyJobs[$company['id']]) ? $companyJobs[$company['id']] : [];
        }
        unset($company);

        $this->success('获取成功', [
            'list' => $companyList,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }

    // 获取招聘会企业详情
    public function getLiveCompanyDetail()
    {
        // 1.get方式获取入参company_id,如果此参数不存在，需要报错
        $companyId = $this->request->get('company_id');
        if (!$companyId) {
            $this->error('参数错误');
        }

        // 2.根据companyId到RecruitmentCompanyModel查询报名企业信息,如果企业信息不存在，也需要报错
        $company = LiveCompanyModel::where('live_company.id', $companyId)
            ->where('status', 1)
            ->with([
                'industry_category' => function($query) { $query->withField('id,name'); },
                'company_scale' => function($query) { $query->withField('id,name'); },
                'company_properties' => function($query) { $query->withField('id,name'); }
            ])
            ->find();
            
        if (!$company) {
            $this->error('企业信息不存在');
        }

        // 3.将industry_category_id,company_scale_id,company_type_id转为对应的名称
        $company['industry_category_name'] = $company['industry_category']['name'] ?? '';
        $company['company_scale_name'] = $company['company_scale']['name'] ?? '';
        $company['company_type_name'] = $company['company_properties']['name'] ?? '';

        // 4.根据company_id到RecruitmentJobModel查询所有岗位记录
        $jobs = LiveJobModel::where('live_company_id', $companyId)
            ->field('id,title,salary,education_level_id,descr')
            ->select();

        // 5.岗位记录中将education_level_id转为对应的文字
        $educationLevels = \app\admin\model\xilujob\EducationLevel::column('name', 'id');
        foreach ($jobs as &$job) {
            $job['education_level_name'] = $educationLevels[$job['education_level_id']] ?? '';
        }
        unset($job);

        // 6.将岗位记录作为企业信息的一个属性后进行返回
        $company['jobs'] = $jobs;
        $company['logo_image'] = cdnurl($company['logo_image'], true);
        unset($company['industry_category'], $company['company_scale'], $company['company_properties']);

        $this->success('获取成功', $company);
    }

    // 申请招聘会企业信息，包括填写职位信息
    public function applyLive()
    {
        $params = input('post.');
        if (empty($params['live_channel_id'])) {
            $this->error('缺少主参数');
        }
        if (empty($params['name'])) {
            $this->error('缺少企业名称');
        }
        if (empty($params['contact_person'])) {
            $this->error('缺少联系人');
        }
        if (empty($params['contact_phone'])) {
            $this->error('缺少联系人电话');
        }
        if (!empty($params['address']) && (empty($params['longitude']) || empty($params['latitude']))) {
            $this->error('有地址信息时，请选择经纬度');
        }
        if (empty($params['logo_image'])) {
            $this->error('请上传企业Logo');
        }
        if (empty($params['other_images'])) {
            $this->error('请上传企业执照或相关证件');
        }
        if (!empty($params['other_images'])) {
            $params['other_images'] = implode(",", $params['other_images']);
        }
        $check = LiveCompanyModel::where('name', 'like', '%'.$params['name'].'%')->find();
        // 如果存在
        $jobs = $params['jobs'];
        unset($params['jobs']);
        if ($check) {
            if ($check->status == '1' || $check->status == '0') {
                $this->error('企业信息重复');
            }
            // 再次提交，标记为未审核
            $check->status = '0';
            $check->name = $params['name'];
            $check->industry_category_id = $params['industry_category_id'];
            $check->company_scale_id = $params['company_scale_id'];
            $check->company_type_id = $params['company_type_id'];
            $check->contact_person = $params['contact_person'];
            $check->contact_phone = $params['contact_phone'];
            $check->address = !empty($params['address']) ? $params['address'] : '';
            $check->longitude = !empty($params['longitude']) ? $params['longitude'] : '';
            $check->latitude = !empty($params['latitude']) ? $params['latitude'] : '';

            $check->intro = $params['intro'];
            $check->logo_image = $params['logo_image'];
            $check->other_images = $params['other_images'];
            $check->save(); 
        } else {
            $check = new LiveCompanyModel();
            $params['job_total'] = count($jobs);
            $check->save($params);
        }
        $companyId = $check->id;

        foreach ($jobs as $job) {
            $jobModel = new LiveJobModel();            
            $job['live_channel_id'] = $params['live_channel_id'];
            $job['live_company_id'] = $companyId;
            $job['status'] = 0;
            $jobModel->save($job);
        }

        $this->success('提交成功，请等待审核!');
    }
}
